from fastapi import APIRouter
from apps.jdnode import llm
from fastapi import FastAPI,WebSocket, WebSocketDisconnect
import requests
#以下是为了解决execjs 报错的问题,必须在execjs 之前加上
from functools import partial  #pip install functoolsplus
import subprocess
subprocess.Popen = partial(subprocess.Popen, encoding='utf-8')
import execjs
import time
from datetime import datetime, timedelta
import os


router = APIRouter()




# @router.post('/edit_node')
# def edit_node(data:datas,id:str = Depends(token.pass_token),db:Session = Depends(init_db)):
# 文生文
@router.websocket("/api") # 访问这个接口需要的地址  ws://127.0.0.1:8088/api)
async def index(websocket: WebSocket):
    await websocket.accept() #创建监听
    try:
        while True:
            data = await websocket.receive_json() #接受json数据
            # print(data)
            if data.get('action') == 'chat':
                # 这里选择AI 通义大模型pip install websockets
                ty = llm.Tongyi('sk-8d774cf840004f028f6c6847c1e57b3d')
                #聊天互动
                response = ty.text_send(data.get('message'))

                message = {
                    'action': 'chat',
                    'type': 'text',  # text 表示文本, image表示图片，
                    'message':  response
                }


                await websocket.send_json(message)

                pass
            elif data.get('action') == 'session':
                print('切换/新增会话记录')
                pass
    except WebSocketDisconnect:
        """表示客户端断开了"""
        pass


# 文生图
@router.post("/api_img")
def apis(msg:dict):
    ty = llm.Tongyi('sk-8d774cf840004f028f6c6847c1e57b3d')
    response = ty.img_send(msg['msg'])
    print(response)

    return response



@router.get("/JSNX")
def JSNX():
    timelist = []
    now = datetime.now()
    # current_date = now.strftime("%Y-%m-%d")
    # timelist.append(current_date)
    #  133213253463  和风天气key 9b865bb070a24fcda8583a3955ae26a2

    api_url = "https://devapi.qweather.com/v7/weather/7d?location=101010100&key=9b865bb070a24fcda8583a3955ae26a2"
    # 发送HTTP请求
    response = requests.get(api_url)
    # print(response.json()['daily'][0])
    if response.status_code == 200:

           # 解析JSON响应
           data = response.json()
           # 打印当天北京的温度
           try:
               for i in data['daily']:
                   temperature = i['fxDate'] #日期
                   tempMax = i['tempMax'] #当天最高温度
                   tempMin = i['tempMin'] #当天最低温度
                   windDirNight = i['windDirNight']  # 天气
                   # print(f"北京当天温度（开尔文）：{temperature}")
                   timelist.append({ 'temperature':temperature,
                                      'tempMax':tempMax,
                                      'tempMin':tempMin,
                                      'windDirNight':windDirNight

                   })


           except KeyError:
               return {'error':'没有获取到数据'}
    else:
           return {'error': '请求失败'}


    return {
           'timelist': timelist
    }
    # print(current_date)
